package com.aurora.app.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSON;
import com.aurora.app.component.SocketSessionManager;
import com.aurora.app.component.SocketSessionManagerImpl;
import com.aurora.app.dao.ChatDao;
import com.aurora.app.dao.ChatGroupDao;
import com.aurora.app.dao.UserDao;
import com.aurora.app.entity.Chat;
import com.aurora.app.entity.ChatGroup;
import com.aurora.app.entity.Message;
import com.aurora.app.entity.User;
import com.aurora.app.enums.ChatMessageType;
import com.aurora.app.enums.MessageType;
import com.aurora.app.service.ChatService;
import com.aurora.app.service.MessageService;

/**
 * Socket处理器
 * 
 * @author Goofy
 * @Date 2015年6月11日 下午1:19:50
 */
@Component
public class MyWebSocketHandler implements WebSocketHandler {

	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	@Resource
	private ChatGroupDao chatGroupDao;
	@Resource
	private UserDao userDao;
	@Resource
	private ChatDao chatDao;
	@Resource
	private ChatService chatService;
	@Resource
	private MessageService messageService;
	@Resource
	private SocketSessionManager socketSessionManager;

	/**
	 * 建立连接后
	 */
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String uid = (String) session.getAttributes().get("uid");
		//socketSessionManager.addUserSocket(uid, session);
		socketSessionManager.addSession(uid, session);
	}

	/**
	 * 消息处理，在客户端通过Websocket API发送的消息会经过这里，然后进行相应的处理
	 */
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		if (message.getPayloadLength() == 0) {
			return;
		}
		try {
			JSONObject obj = new JSONObject(message.getPayload().toString());
			sendMessageToUser(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 消息传输错误处理
	 */
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		LOG.info("news transafrom error");
		socketSessionManager.remove(session);
	}

	/**
	 * 关闭连接后
	 */
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		LOG.info("socket closed");
		socketSessionManager.remove(session);
	}

	public boolean supportsPartialMessages() {
		return false;
	}

	/**
	 * 用户给某个用户发送消息
	 * @throws JSONException 
	 * @throws IOException 
	 * 
	 */
	public void sendMessageToUser(JSONObject obj) throws JSONException, IOException{
		// 聊天组
		String chatGroupId = (String) obj.get("chatGroupId");
		String fromId = (String) obj.get("from");
		String toId = (String) obj.get("to");
		String msg = (String) obj.get("msg");
		String usage = (String) obj.get("usage");
		int chatMessageType = (int) obj.get("chatMessageType");
		if (StringUtils.isBlank(chatGroupId) || StringUtils.isBlank(fromId) || StringUtils.isBlank(toId)) {
			return;
		}
		Chat chat = new Chat();
		ChatGroup chatGroup = this.chatGroupDao.find(chatGroupId);
		User from = this.userDao.find(fromId);
		User to = this.userDao.find(toId);

		if (chatGroup == null || from == null || to == null) {
			return;
		}
		chat.setChatGroup(chatGroup);
		chat.setUser(from);
		chat.setToUser(to);
		chat.setMessage(msg);
		switch (chatMessageType) {
		case 0:
			chat.setChatMessageType(ChatMessageType.TEXT);
			break;
		case 1:
			chat.setChatMessageType(ChatMessageType.AUDIO);
			break;
		case 2:
			chat.setChatMessageType(ChatMessageType.PICTURE);
			break;
		case 3:
			chat.setChatMessageType(ChatMessageType.URL);
			break;
		default:
			chat.setChatMessageType(ChatMessageType.TEXT);
			break;
		}
		this.chatService.save(chat);
		LOG.info(chat.toString());
		WebSocketSession session = socketSessionManager.getSession(chat.getToUser().getId());
		if (session != null && session.isOpen()){
			if(socketSessionManager.isCanSend(session.getId(), chat.getUser().getId(), usage)){
				JSONObject objTo = new JSONObject();
					objTo.put("img", chat.getUser().getHeadimgurl());
					objTo.put("msg", chat.getMessage());
					String str = "{\"img\":\"" + chat.getUser().getHeadimgurl() + "\",\"msg\":\"" + chat.getMessage()
							+ "\"}";
					LOG.info(JSON.toJSONString(objTo));
					LOG.info(str);
					session.sendMessage(new TextMessage(str));
			}
		}
		// 存进提醒消息类
		// 检查是否应该添加
		if (this.messageService.checkTheChatTypeMsgShouldAdd(chat.getToUser().getId(), chat.getChatGroup().getId())) {
			Message message = new Message();
			message.setUser(chat.getUser());
			message.setIsRead(false);
			message.setMessage("您有一则聊天消息！");
			message.setMessageType(MessageType.Chat);
			message.setUrl("api/chat/withThing.do?CHATGROUPID=" + chat.getChatGroup().getId());
			message.setToUser(chat.getToUser());
			Map<String, String> map = new HashMap<String, String>();
			map.put("CHATGROUP", chat.getChatGroup().getId());
			message.setTip(JSON.toJSONString(map));
			this.messageService.save(message);
		}
	}
	
	
	
//	public void sendMessageToUser(Chat chat) throws IOException {
//		WebSocketSession session = socketSessionManager.getSession(chat.getToUser().getId());
//		if (session != null && session.isOpen()) {
//			//不被占用的情况下，向用户发送信息
//			if(!socketSessionManager.isOccupy(session.getId(), chat.getUser().getId(),chat.getChatGroup().getThing().getId())){
//				JSONObject obj = new JSONObject();
//				try {
//					obj.put("img", chat.getUser().getHeadimgurl());
//					obj.put("msg", chat.getMessage());
//					String str = "{\"img\":\"" + chat.getUser().getHeadimgurl() + "\",\"msg\":\"" + chat.getMessage()
//							+ "\"}";
//					LOG.info(JSON.toJSONString(obj));
//					LOG.info(str);
//					session.sendMessage(new TextMessage(str));
//				} catch (JSONException e) {
//					e.printStackTrace();
//				}
//			};
//		}
//		// 存进提醒消息类
//		// 检查是否应该添加
//		if (this.messageService.checkTheChatTypeMsgShouldAdd(chat.getToUser().getId(), chat.getChatGroup().getId())) {
//			Message message = new Message();
//			message.setUser(chat.getUser());
//			message.setIsRead(false);
//			message.setMessage("您有一则聊天消息！");
//			message.setMessageType(MessageType.Chat);
//			message.setUrl("api/chat/withThing.do?CHATGROUPID=" + chat.getChatGroup().getId());
//			message.setToUser(chat.getToUser());
//			Map<String, String> map = new HashMap<String, String>();
//			map.put("CHATGROUP", chat.getChatGroup().getId());
//			message.setTip(JSON.toJSONString(map));
//			this.messageService.save(message);
//		}
//
//	}

}
